import { useState, useEffect } from 'preact/hooks';
import { isConnected, ethercatData } from '../app';

export default function EtherCATSlave() {

  // 获取EtherCAT实际数据
  useEffect(() => {
    if (!isConnected.value) return;

    const fetchEthercatData = async () => {
      try {
        const response = await fetch('/api/ethercat/data');
        if (response.ok) {
          const data = await response.json();
          ethercatData.value = {
            digitalInputs: data.digitalInputs,
            digitalOutputs: data.digitalOutputs,
            syncPeriod: data.syncPeriod,
            syncMode: data.syncMode,
            slaveALStatus: data.slaveALStatus
          };
        } else {
          console.error('EtherCAT数据获取失败:', response.status);
        }
      } catch (error) {
        console.error('EtherCAT数据获取失败:', error);
      }
    };

    // 立即获取一次
    fetchEthercatData();
    
    // 设置500ms更新周期
    const interval = setInterval(fetchEthercatData, 500);
    return () => clearInterval(interval);
  }, [isConnected.value]);

  const getStatusBadgeClass = (status) => {
    switch (status) {
      case 'OP': return 'adonis-badge adonis-badge-success';
      case 'SAFEOP': return 'adonis-badge adonis-badge-warning';
      case 'PREOP': return 'adonis-badge adonis-badge-info';
      case 'INIT': return 'adonis-badge adonis-badge-muted';
      default: return 'adonis-badge';
    }
  };

  return (
    <div class="h-full p-6">
      <div class="flex justify-between items-center mb-6">
        <h1 class="text-xl font-medium flex items-center adonis-section-title">
          <div class="w-1 h-5 mr-3" style={{ background: 'var(--adonis-accent)' }}></div>
          EtherCAT Slave
        </h1>
        <div class="flex items-center space-x-4">
          <div class="flex items-center" style={{ color: 'var(--adonis-text-muted)' }}>
            <div class={`w-3 h-3 rounded-full mr-2 ${isConnected.value ? 'animate-pulse' : ''}`} style={{ background: isConnected.value ? 'var(--adonis-success)' : 'var(--adonis-danger)' }}></div>
            <span class="text-sm">
              {isConnected.value ? '已连接' : '未连接'}
            </span>
          </div>
        </div>
      </div>

      {/* EtherCAT状态概览 */}
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        {typeof ethercatData.value?.slaveALStatus === 'string' && (
          <div class="adonis-card p-4">
            <h3 class="text-sm adonis-section-title mb-2">从站状态</h3>
            <div class={getStatusBadgeClass(ethercatData.value.slaveALStatus)}>
              {ethercatData.value.slaveALStatus}
            </div>
          </div>
        )}
        {typeof ethercatData.value?.syncMode === 'string' && (
          <div class="adonis-card p-4">
            <h3 class="text-sm adonis-section-title mb-2">同步模式</h3>
            <div class="text-lg font-semibold" style={{ color: 'var(--adonis-accent)' }}>
              {ethercatData.value.syncMode}
            </div>
          </div>
        )}
        {typeof ethercatData.value?.syncPeriod === 'number' && (
          <div class="adonis-card p-4">
            <h3 class="text-sm adonis-section-title mb-2">同步周期</h3>
            <div class="text-lg font-semibold">
              {ethercatData.value.syncPeriod.toFixed(1)} μs
            </div>
          </div>
        )}
      </div>

      {/* 数字输入 */}
      {typeof ethercatData.value?.digitalInputs === 'number' && (
        <div class="adonis-card p-6 mb-6">
          <h2 class="text-lg font-semibold adonis-section-title mb-4">
            DI-16
          </h2>
          <div class="grid grid-cols-8 gap-3">
            {Array.from({length: 16}, (_, index) => {
              const state = (ethercatData.value.digitalInputs >> index) & 1;
              return (
                <div key={index} class="flex flex-col items-center">
                  <div class={`relative w-12 h-12 rounded-lg flex items-center justify-center mb-2 overflow-hidden`}
                       style={{ 
                         background: state === 1 
                           ? 'linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)' 
                           : 'linear-gradient(135deg, var(--adonis-panel-2) 0%, var(--adonis-panel) 100%)',
                         border: '1px solid',
                         borderColor: state === 1 ? '#3b82f6' : 'var(--adonis-border)',
                         boxShadow: state === 1 
                           ? '0 0 8px rgba(59, 130, 246, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1)' 
                           : '0 2px 4px rgba(0, 0, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.05)'
                       }}>
                    <span class="text-lg font-mono font-bold tracking-wider" style={{ 
                      color: state === 1 ? '#ffffff' : 'var(--adonis-accent)',
                      textShadow: 'none'
                    }}>
                      {state}
                    </span>
                    <div class="absolute inset-0 rounded-lg opacity-20" style={{
                      background: state === 1 
                        ? 'linear-gradient(45deg, transparent 30%, rgba(59, 130, 246, 0.2) 50%, transparent 70%)'
                        : 'linear-gradient(45deg, transparent 30%, rgba(59, 130, 246, 0.05) 50%, transparent 70%)',
                      animation: state === 1 ? 'scan 3s linear infinite' : 'none'
                    }}></div>
                  </div>
                  <span class="text-xs font-mono" style={{ color: 'var(--adonis-text-muted)' }}>IN{index + 1}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* 数字输出 */}
      {typeof ethercatData.value?.digitalOutputs === 'number' && (
        <div class="adonis-card p-6 mb-6">
          <h2 class="text-lg font-semibold adonis-section-title mb-4">
            DO-16
          </h2>
          <div class="grid grid-cols-8 gap-3">
            {Array.from({length: 16}, (_, index) => {
              const state = (ethercatData.value.digitalOutputs >> index) & 1;
              return (
                <div key={index} class="flex flex-col items-center">
                  <div class={`relative w-12 h-12 rounded-lg flex items-center justify-center mb-2 overflow-hidden`}
                       style={{ 
                         background: state === 1 
                           ? 'linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)' 
                           : 'linear-gradient(135deg, var(--adonis-panel-2) 0%, var(--adonis-panel) 100%)',
                         border: '1px solid',
                         borderColor: state === 1 ? '#3b82f6' : 'var(--adonis-border)',
                         boxShadow: state === 1 
                           ? '0 0 8px rgba(59, 130, 246, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1)' 
                           : '0 2px 4px rgba(0, 0, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.05)'
                       }}>
                    <span class="text-lg font-mono font-bold tracking-wider" style={{ 
                      color: state === 1 ? '#ffffff' : 'var(--adonis-accent)',
                      textShadow: 'none'
                    }}>
                      {state}
                    </span>
                    <div class="absolute inset-0 rounded-lg opacity-20" style={{
                      background: state === 1 
                        ? 'linear-gradient(45deg, transparent 30%, rgba(59, 130, 246, 0.2) 50%, transparent 70%)'
                        : 'linear-gradient(45deg, transparent 30%, rgba(59, 130, 246, 0.05) 50%, transparent 70%)',
                      animation: state === 1 ? 'scan 3s linear infinite' : 'none'
                    }}></div>
                  </div>
                  <span class="text-xs font-mono" style={{ color: 'var(--adonis-text-muted)' }}>OUT{index + 1}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

    </div>
  );
}
